package M

import (
	"fmt"
	"strconv"
	"strings"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

//_ "github.com/mattn/go-sqlite3"
//_ "github.com/go-sql-driver/mysql"
func Gorm(con DBconfig) *gorm.DB {
	con.Type = strings.ToLower(con.Type)
	if con.Port == 0 {
		con.Port = 3306
	}
	if con.Charset == "" {
		con.Charset = "utf8"
	}
	if con.Server == "" {
		con.Server = "127.0.0.1"
	}
	if con.Type == "mysql" {
		dns := con.UserName + ":" + con.UserPass + "@tcp(" + con.Server + ":" + strconv.Itoa(con.Port) + ")/" + con.DbName + "?charset=" + con.Charset + "&parseTime=True&loc=Local"

		db, err := gorm.Open(mysql.Open(dns), &gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				TablePrefix:   con.Prefix,
				SingularTable: true,
			},
		})
		if err != nil {
			fmt.Println("数据库连接错误")
			return nil
		}
		return db
	}
	if con.Type == "sqlite" {
		db, err := gorm.Open(sqlite.Open(con.Server), &gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				TablePrefix:   con.Prefix,
				SingularTable: true,
			},
		})
		if err != nil {
			fmt.Println("数据库连接错误")
			return nil
		}
		return db
	}
	return nil
}
